SOLID SRP Example in Scala

Problem Statement:

Consider a class Employee that handles both employee information and file operations:

        
class Employee(name: String, employeeId: String) {
  // ... other properties and methods ...

  def saveToFile(): Unit = {
    // logic to save employee details to a file
  }

  def loadFromFile(): Unit = {
    // logic to load employee details from a file
  }
}
        
    

This violates SRP as the Employee class has multiple reasons to change: one for employee information and another for file operations.

Solution - Applying SRP:

Separate concerns by creating a separate class for file operations:

        
class Employee(name: String, employeeId: String) {
  // ... other properties and methods ...
}

class EmployeeFileHandler {
  def saveToFile(employee: Employee): Unit = {
    // logic to save employee details to a file
  }

  def loadFromFile(employeeId: String): Employee = {
    // logic to load employee details from a file
    // return loaded employee object
  }
}
        
    

Now, the Employee class focuses solely on employee-related functionality, adhering to the Single Responsibility Principle.

Benefits: